package com.wuyong.chapter7;

/**
 * 链表实现Map
 * @param <K>
 * @param <V>
 */
public class LinkedListMap<K, V> implements Map<K, V> {

    private class Node {
        private K key;
        private V value;
        private Node next;

        public Node(K key, V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public Node(K key) {
            this.key = key;
            this.value = null;
            this.next = null;
        }

        public Node() {
            this.key = null;
            this.value = value;
            this.next = null;
        }

        @Override
        public String toString() {
                return key.toString() + " : " + value.toString();
        }
    }
    private Node dummyHead;
    private int size;

    public LinkedListMap() {
        dummyHead = new Node();
        size =  0;
    }

    private Node getNode(K k) {
        Node cur = dummyHead.next;
        while (cur != null) {
            if(cur.key.equals(k))
                return cur;
            cur = cur.next;
        }
        return null;
    }
    @Override
    public void add(K k, V v) {
        Node node = getNode(k);
        if (node == null) {
            dummyHead.next = new Node(k, v, dummyHead.next);
            size++;
        }else {
            node.value = v;
        }
    }

    @Override
    public V remove(K k) {

        Node prev = dummyHead;
        while(prev.next != null){
            if(prev.next.key.equals(k))
                break;
            prev = prev.next;
        }

        if(prev.next != null){
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            size --;
            return delNode.value;
        }
        return null;
    }

    @Override
    public boolean contains(K k) {
        return getNode(k) == null ? false:true;
    }

    @Override
    public V get(K k) {
        return getNode(k) == null ? null : getNode(k).value;
    }

    @Override
    public void set(K k, V v) {
        Node node = getNode(k);
        if (node == null)
            throw new IllegalArgumentException("key 重复");
        node.value = v;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }
}
